import { QaActionType } from '../actions/qaAction'
import { Type, Data } from '../utils/Global'
import { Storage, Keys } from '../utils/LocalStorage'
import { cloneDeep } from 'lodash'

const qa_state = {
  list: [],
  width: 0,
  footer_value: '',
  link_list: [],
  select_links: [],
  link_loading: false,
  show_link: false,
  search_value: '',
  big_image_url: '',
  voice_status: {},
  new_msg_count: 0
}

const QaState = (state = qa_state, action) => {
  let cloneState = cloneDeep(state)
  switch (action.type) {
    case QaActionType.set_list_width:
      return Object.assign({}, state, {
        width: action.width
      })
    case QaActionType.toggle_link_loading:
      return Object.assign({}, state, {
        link_loading: action.loading
      })
    case QaActionType.init_link_list:
      cloneState.link_list = action.list
      return cloneState
    case QaActionType.set_footer_value:
      return Object.assign({}, state, {
        footer_value: action.value
      })
    case QaActionType.set_search_value:
      return Object.assign({}, state, {
        search_value: action.value
      })
    case QaActionType.set_select_links:
      return Object.assign({}, state, {
        select_links: action.links
      })
    case QaActionType.toggle_show_link:
      return Object.assign({}, state, {
        show_link: action.show
      })
    case QaActionType.toggle_big_image:
      return Object.assign({}, state, {
        big_image_url: action.url
      })
    
    case QaActionType.update_new_msg_count:
      const count = action.setZero ? 0 : (state.new_msg_count + 1)
      return Object.assign({}, state, {
        new_msg_count: count
      })
    default:
      return state
  }
}
const initVoiceStatus = (list) => {
  const obj = {}
  const hasPlayedVoiceList = Storage.read(Keys.QA_VOICE_KEY) || []
  list.map((item, index) => {
    if (item.type === Type.COMMON_TYPE.COMMON_QA_VOICE) {
      obj[item.data.file] = {
        playing: false,
        hasPlayed: hasPlayedVoiceList.indexOf(item.data.file) >= 0,
        loading: false,
        error: false
      }
    }
  })
  return obj
}
const initList = (list) => {
  const hasPlayedVoiceList = Storage.read(Keys.QA_VOICE_KEY) || []
  return list.map((msg) => {
    if (msg.type === Type.COMMON_TYPE.COMMON_QA_VOICE) {
      msg.voiceStatus = {
        playing: false,
        hasPlayed: hasPlayedVoiceList.indexOf(msg.data.file) >= 0,
        loading: false,
        error: false
      }
    }
    return msg
  })
}
const insertVoiceStatus = (msg) => {
  const obj = {}
  if (msg.type === Type.COMMON_TYPE.COMMON_QA_VOICE) {
    obj[msg.data.file] = {
      playing: false,
      hasPlayed: Data.user.id === msg.sender.id,
      loading: false,
      error: false
    }
  }
  return obj
}
QaState._default_state = qa_state
export default QaState
